package com.bxx.ermall.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bxx.ermall.common.dto.LoginDto;
import com.bxx.ermall.common.dto.RegisterDto;
import com.bxx.ermall.common.lang.Result;
import com.bxx.ermall.entity.Member;
import com.bxx.ermall.service.MemberService;
import com.bxx.ermall.util.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author buxiaoxing
 * @since 2021-02-02
 */
@RestController
public class MemberController {

    @Autowired
    MemberService memberService;


    @Autowired
    JwtUtils jwtUtils;
    //登录
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response){
        Member user = memberService.getOne(new QueryWrapper<Member>().eq("login_name", loginDto.getLoginName()));
        Assert.notNull(user, "用户不存在");

//        System.out.println(user.getPassword()+":"+ SecureUtil.md5(loginDto.getPassword()));
        if(!user.getPassword().equals(loginDto.getPassword())){
            return Result.fail("密码不正确");
        }
        String jwt = jwtUtils.generateToken(user.getId());

        response.setHeader("Authorization", jwt);
        response.setHeader("Access-control-Expose-Headers", "Authorization");

        return Result.succ(MapUtil.builder()
                .put("userName", user.getUserName())
                .put("avatar", user.getAvatar())
                .map()
        );
    }
    //注册
    @PostMapping("/register")
    public Result register(@Validated @RequestBody RegisterDto registerDto){
        Member user = memberService.getOne(new QueryWrapper<Member>().eq("login_name", registerDto.getLoginName()));
        if(user != null){
            return  Result.fail("手机号已被注册");
        }else{
            Member newUser = new Member();
            newUser.setGrade(1);
            BeanUtil.copyProperties(registerDto, newUser, "id", "grade");
            memberService.save(newUser);
            Member user2 = memberService.getOne(new QueryWrapper<Member>().eq("login_name",registerDto.getLoginName()));
            return Result.succ(user2);
        }
    }
    //注销
    @RequiresAuthentication
    @GetMapping("/logout")
    public Result logout(){
        SecurityUtils.getSubject().logout();
        return Result.succ(null);
    }
}

